import dayjs from "dayjs";
import utils from "~/utils";
import * as lodash from "lodash";

/**
 * 时间戳处理
 * @param timeSection
 */
export function timeSectionDeal(timeSection: string): number[] {
    if (!utils.text.isEmpty(timeSection)) {
        let [startCreatedAt, endCreatedAt] = timeSection.split(',');
        // 格式化时间戳
        if (!utils.text.isEmpty(startCreatedAt) && !utils.text.isEmpty(endCreatedAt)) {
            let startCreateAtMoment = dayjs(startCreatedAt);
            let endCreatedAtMoment = dayjs(endCreatedAt);
            // 验证有效性
            if (startCreateAtMoment.isValid() && endCreatedAtMoment.isValid()) {
                return [startCreateAtMoment.startOf('days').valueOf(), endCreatedAtMoment.endOf('days').valueOf()];
            }
        }
    }
    return [0, 0];
}

/**
 * 格式化日期
 * @param datetime
 * @returns
 */
export function formatWeek(datetime: number) {
    let weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    let week = Number(dayjs(datetime).format('d'));
    return weekArr[week];
}

/**
 * am、pm上午语义化
 * @param datetime
 * @returns
 */
export function formatAmPm(datetime: number) {
    let str = dayjs(datetime).format('a');
    return str.toLocaleLowerCase() === 'am' ? '上午' : '下午';
}

/**
 * 获取当前时间戳
 * @returns
 */
export function timestamp(timestamp?: number): number {
    if (utils.text.isEmpty(timestamp)) {
        return Number((dayjs().valueOf() / 1000).toFixed(0));
    } else {
        return Number((dayjs(timestamp).valueOf() / 1000).toFixed(0));
    }
}

/**
 * 获取两个时间之前的完整月份数量
 * @param startTime
 * @param endTime
 * @returns
 */
export function timeCompleteMonthDiff(startTime: any, endTime: any): number {
    startTime = dayjs(startTime).valueOf();
    endTime = dayjs(endTime).valueOf();
    let complete_days = 0;
    let months = 0;
    for (let i = dayjs(startTime).year(); i <= dayjs(endTime).year(); i++) {
        let start = 1;
        let end = 12;
        if (dayjs(startTime).year() === dayjs(endTime).year()) {
            start = dayjs(startTime).month() + 1;
            end = dayjs(endTime).month() + 1;
        } else {
            if (i === dayjs(startTime).year()) {
                start = dayjs(startTime).month() + 1;
            } else {
                if (i === dayjs(endTime).year()) {
                    end = dayjs(endTime).month() + 1;
                }
            }
        }

        for (let m = start; m <= end; m++) {
            complete_days += dayjs(i + '-' + (m < 10 ? '0' + m : m)).daysInMonth();
            months++;
        }
    }
    let timeDayDiff = dayjs(endTime).diff(startTime, 'days');
    return (timeDayDiff === complete_days - 1) ? months : 0;
}

/**
 * 20220706102316 转 2022-07-06 10:23:16
 * @param date
 */
export function formatStringToTimestamp(date: any) {
    date = date.replace(/[^0-9]/g, '');
    // 去除空格
    date = date.replace(/\s*/g, "");
    // 去除 -
    date = date.replace(/-/g, "");
    // 去除 :
    date = date.replace(/：/g, "");
    date = date.replace(/:/g, "");

    if (date.length !== 14) {
        return 0;
    }

    date = date.slice(0, 4) + "-" + date.slice(4); // 2022-0706102316
    date = date.slice(0, 7) + "-" + date.slice(7); // 2022-07-06102316
    date = date.slice(0, 10) + " " + date.slice(10);
    date = date.slice(0, 13) + ":" + date.slice(13);
    date = date.slice(0, 16) + ":" + date.slice(16);
    return date;
}

/**
 * 时间差值语义化
 * @param startTime
 * @param endTime
 */
export function timeDiffFormat(startTime: number, endTime: number) {
    let startDate = {
        'year': Number(dayjs(startTime)
            .format('YYYY')),
        'month': Number(dayjs(startTime)
            .format('MM')),
        'day': Number(dayjs(startTime)
            .format('DD'))
    };
    let endDate = {
        'year': Number(dayjs(endTime)
            .format('YYYY')),
        'month': Number(dayjs(endTime)
            .format('MM')),
        'day': Number(dayjs(endTime)
            .format('DD'))
    };

    let year = 0;
    let month = 0;
    let day = 0;
    let monthMap = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 };
    if (endDate['day'] >= startDate['day']) { // 天相减为正
        if (endDate['month'] >= startDate['month']) { // 月相减为正
            year = endDate['year'] - startDate['year'];
            month = endDate['month'] - startDate['month'];
        } else { // 月相减为负，借年
            year = endDate['year'] - startDate['year'] - 1;
            month = endDate['month'] - startDate['month'] + 12;
        }
        day = endDate['day'] - startDate['day'];
    } else { // 天相减为负，借月
        if (endDate['month'] === 1) { // 1月，借年
            year = endDate['year'] - startDate['year'] - 1;
            month = endDate['month'] - startDate['month'] + 12;
            day = endDate['day'] - startDate['day'] + monthMap[12];
        } else {
            if (endDate['month'] === 3) { // 3月，判断闰年取得2月天数
                day = endDate['day'] - startDate['day'] + (endDate['year'] % 4 === 0 ? 29 : 28);
            } else {
                day = endDate['day'] - startDate['day'] + monthMap[endDate['month'] - 1];
            }
            if (endDate['month'] >= startDate['month'] + 1) { // 借月后，月相减为正
                year = endDate['year'] - startDate['year'];
                month = endDate['month'] - startDate['month'] - 1;
            } else { // 借月后，月相减为负，借年
                year = endDate['year'] - startDate['year'] - 1;
                month = endDate['month'] - startDate['month'] + 12 - 1;
            }
        }
    }

    return {
        'year': year,
        'month': month,
        'day': day
    };
}

/**
 * 获取指定日期，后面几个月包含当前月
 * @param timestamp 
 * @param num 
 * @returns 
 */
export function getMonths(timestamp = 0, num = 36) {
    if (timestamp === 0) {
        timestamp = dayjs().startOf('M').valueOf();
    }
    let data: Array<any> = [];
    for (let i = 0; i < num; i++) {
        let temp = dayjs(timestamp).add(i, 'M').format("YYYY/MM");

        data.push({
            label: temp,
            st_date: dayjs(temp).startOf('month').format("YYYY-MM-DD"),
            st_timestap: dayjs(temp).startOf('month').valueOf(),
            ed_date: dayjs(temp).endOf('month').format("YYYY-MM-DD"),
            ed_timestap: dayjs(temp).endOf('month').valueOf(),
        });
    }
    return data;
}

/**
 * 获取指定日期，后面几个年费包含当前年
 * @param timestamp 
 * @param num 
 * @returns 
 */
export function getYears(timestamp = 0, num = 3) {
    if (timestamp === 0) {
        timestamp = dayjs().startOf('y').valueOf();
    }
    let data: Array<any> = [];
    for (let i = 0; i < num; i++) {
        let temp = dayjs(timestamp).add(i, 'y').format("YYYY");
        data.push({
            label: temp,
            st_date: dayjs(temp).startOf('year').format("YYYY-MM-DD"),
            st_timestap: dayjs(temp).startOf('year').valueOf(),
            ed_date: dayjs(temp).endOf('year').format("YYYY-MM-DD"),
            ed_timestap: dayjs(temp).endOf('year').valueOf()
        });
    }
    return data;
}

/**
 * 获取指定日期，后面几个季度包含当前季度
 * @param timestamp 
 * @param num 
 * @returns 
 */
export function getQuarterlys(timestamp = 0, num = 12) {
    let quarterOfYear = require('dayjs/plugin/quarterOfYear');
    dayjs.extend(quarterOfYear);

    if (timestamp === 0) {
        timestamp = dayjs().startOf('M').valueOf();
    }

    let data: Array<any> = [];

    // for (let i = 0; i < num; i++) {
    //     let temp = dayjs(timestamp).add(i, 'quarter').valueOf();
    //     data.push({
    //         label: dayjs(temp).format("YYYY") + 'Q' + dayjs(temp).quarter(),
    //         // label: dayjs(temp).format("YYYY") + '/Q' + dayjs(temp).quarter(),
    //         st_date: dayjs(temp).startOf("quarter").format("YYYY-MM-DD"),
    //         st_timestap: dayjs(temp).startOf("quarter").valueOf(),
    //         ed_date: dayjs(temp).endOf("quarter").format("YYYY-MM-DD"),
    //         ed_timestap: dayjs(temp).endOf("quarter").valueOf(),
    //     });
    //
    // }

    return data;
}

/**
 * 获取指定开始日期和结束日期之间的每天时间戳
 */
export function getTimestampsInRange(startDate: string | number, endDate: string | number): number[] {
    const timestamps: number[] = [];

    let currentDate = dayjs(startDate).startOf('day');
    const lastDate = dayjs(endDate).startOf('day');

    // while (currentDate.isSameOrBefore(lastDate)) {
    //     timestamps.push(currentDate.valueOf());
    //     currentDate = currentDate.add(1, 'day');
    // }

    return timestamps;
}

/**
 * 判断是否是完整的一个月
 * @param startDate 
 * @param endDate 
 * @returns 
 */
export function isWholeMonth(startDate: string | number, endDate: string | number): boolean {
    const start = dayjs(startDate);
    const end = dayjs(endDate);
    return start.isSame(end, 'month') && start.date() === 1 && end.date() === start.daysInMonth();
}

/**
 * 获取近6个月
 */
export function getLast6Month() {
    const timestamps: number[] = [];
    let currentDate = dayjs();

    for (let i = 0; i < 6; i++) {
        timestamps.push(currentDate.startOf('M').valueOf());
        currentDate = currentDate.subtract(1, 'month');
    }
    return lodash.reverse(timestamps);
}
/**
 * 获取指定开始日期和结束日期之间的每个月
 */
export function getMonthInRange(startDate: string | number, endDate: string | number): number[] {

    let data: Array<any> = [];

    let currentDate = dayjs(startDate).startOf('day');

    const lastDate = dayjs(endDate).startOf('day');

    console.log(currentDate.format("YYYY-MM-DD"), '---xx1');
    console.log(currentDate.format("YYYY-MM-DD"), '---xx2');

    // while (currentDate.isSameOrBefore(lastDate)) {
    //
    //     let temp = dayjs(currentDate).valueOf();
    //     data.push({
    //         label: dayjs(temp).format("YYYY/MM"),
    //         st_date: dayjs(temp).startOf("month").format("YYYY-MM-DD"),
    //         st_timestap: dayjs(temp).startOf("month").valueOf(),
    //         ed_date: dayjs(temp).endOf("month").format("YYYY-MM-DD"),
    //         ed_timestap: dayjs(temp).endOf("month").valueOf(),
    //     });
    //     currentDate = currentDate.add(1, 'month');
    // }

    return data;
}